package com.zhilianbao.leyaogo.ui.fragment.goodscategory;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.roundview.RoundTextView;
import com.bql.sharesdk.utils.ShareUtil;
import com.bql.utils.EventManager;
import com.jakewharton.rxbinding.view.RxView;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.model.response.category.GoodsDetails;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.shoppingcart.ShoppingCartActivity;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopNumUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.CustomViewPager;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;
import rx.Subscription;
import rx.functions.Action1;


/**
 * 商品页面
 * Created by gyt on 2016/11/1
 */
public class GoodsFragment extends BaseOkHttpFragment {


    @BindView(R.id.viewpager)
    CustomViewPager mViewpager;
    @BindView(R.id.tabLayout)
    TabLayout       mTabLayout;
    @BindView(R.id.tv_details_toolbar)
    TextView        mTvDetailsToolbar;
    @BindView(R.id.ll_left_container)
    LinearLayout    mLlLeftContainer;
    @BindView(R.id.ll_shopping_cart)
    LinearLayout    mLlShoppingCart;
    @BindView(R.id.ll_collect_goods)
    LinearLayout    mLlCollectGoods;
    @BindView(R.id.tv_add_to_cart)
    TextView        mTvAddToCart;
    @BindView(R.id.tv_collect_goods)
    TextView        mTvCollectGoods;
    @BindView(R.id.ll_bottom)
    LinearLayout    mLlBottom;
    @BindView(R.id.rtv_cart_num)
    RoundTextView   mRtvCartNum;
    @BindView(R.id.iv_collect_goods)
    ImageView       mIvCollectGoods;
    @BindView(R.id.iv_share)
    ImageView       mIvShare;


    private String[]   mTitles;
    private Fragment[] mFragments;
    // 商品是否已经收藏
    private boolean    isCollected;
    // 购物车中的数量
    private int cartNum = 0;

    private boolean netError = false;
    private GoodsDetails mGoodsDetails;
    private Subscription mSubscription;
    // 当该fragment隐藏后，就不再接收eventBus发来的goodsDetail数据
    private boolean mRefuse = false;
    private boolean mIsFromCart;

    // 收藏商品和取消收藏
    private static final int TYPE_COLLECT = 1;
    private static final int TYPE_CANCEL  = 0;


    public static GoodsFragment getInstance(Bundle bundle) {
        GoodsFragment fragment = new GoodsFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_goods;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        // 初始化shareSDK
        ShareUtil.initSDK(mActivity);
        CLog.i("initViewsAndEvents=============");
        Bundle bundle = getArguments();
        if (bundle == null) {
            return;
        }

        mIsFromCart = bundle.getBoolean(IntentConfig.IS_FROM_SHOPPING_CART, false);
        GoodsInfoFragment goodsInfoFragment = GoodsInfoFragment.getInstance(bundle);
        GoodsDetailsFragment goodsDetailsFragment = GoodsDetailsFragment.getInstance();
        mFragments = new Fragment[]{goodsInfoFragment, goodsDetailsFragment};

        goodsDetailsFragment.setOnBackPressedListener(new GoodsDetailsFragment.OnBackPressedListener() {
            @Override
            public void onBackPressed() {
                mViewpager.setCurrentItem(0, true);
            }
        });

        mTitles = getResources().getStringArray(R.array.Goods_TabLayout_Title);
        GoodsViewPagerAdapter adapter = new GoodsViewPagerAdapter(mActivity.getSupportFragmentManager());
        mViewpager.setAdapter(adapter);
        mViewpager.setPagingEnabled(true);
        // 设置viewPager中缓存的数量
        mViewpager.setOffscreenPageLimit(mFragments.length);
        mTabLayout.setupWithViewPager(mViewpager);
        // 数据没加载出来，tab不可以点击切换详情页
        setTabClickable(false);
        isViewPagerEnable(false);

        mLlCollectGoods.setEnabled(false);
        mLlShoppingCart.setEnabled(false);
        mTvAddToCart.setEnabled(false);

        //加入购物车按钮防多次点击处理，一秒只能点击一次
        mSubscription = RxView.clicks(mTvAddToCart)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        if (!netError) {
                            addToCart();
                        }
                    }
                });
        setCartNum();
    }

    /**
     * tab是否可以点击
     * @param clickable
     */
    private void setTabClickable(boolean clickable) {
        LinearLayout tabStrip = (LinearLayout) mTabLayout.getChildAt(0);
        for (int i = 0; i < tabStrip.getChildCount(); i++) {
            View tabView = tabStrip.getChildAt(i);
            if (tabView != null) {
                tabView.setClickable(clickable);
            }
        }
    }

    private void setCartNum() {
        // 设置购物车数量
        cartNum = LeYaoGoApplication.SHOPPING_CART_NUM;
        CLog.i("cartNum=======================" + cartNum);
        ShopNumUtils.show(mRtvCartNum, cartNum);
    }


    @Override
    protected void initToolbarHere() {
        bindToolbar();
    }

    @OnClick({R.id.ll_shopping_cart, R.id.ll_collect_goods, R.id.ll_left_container, R.id.iv_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_left_container:
                mActivity.onBackPressed();
                break;
            case R.id.ll_shopping_cart:
                Utils.startActivity(mActivity, ShoppingCartActivity.class);
                break;
            case R.id.ll_collect_goods:
                CLog.d("neterror = " + netError);
                if (!netError) {
                    collectGoods(isCollected ? TYPE_CANCEL : TYPE_COLLECT);
                }
                break;
            case R.id.iv_share:
                Utils.showShare(mActivity, mGoodsDetails.getGoodsName(), mGoodsDetails.getGoodsFullName(), Utils.returnUrlShow(mGoodsDetails.getGoodsPic()));
                break;
        }
    }

    /**
     * 收藏商品
     */
    private void collectGoods(int type) {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.CollectGoods.value)) {
            CategoryApi.setMyCollectionGoods(mActivity, type, Utils.getUserLoginInfo().getUserId(), Utils.getSupplierId(), 1, mGoodsDetails.getShopId(), mGoodsDetails.getGoodsId(), mGoodsDetails.getGoodsSkuId(), new DialogCallback<Object>(mActivity) {
                @Override
                public void onSuccess(Object o, Call call, Response response) {
                    if (type == TYPE_COLLECT) {
                        XToastUtils.showShortToast(R.string.msg_collect_sucs);
                        isCollected = true;
                    } else {
                        XToastUtils.showShortToast(R.string.msg_cancle_collect_sucs);
                        isCollected = false;
                    }
                    collectGoodsAnim();
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SET_COLLECTION_SUCCESS));
                }
            });
        } else {
            XToastUtils.showShortToast(R.string.msg_login_to_collect_goods);
            LogicCodeBlock.create().registerLogicCodeCallback(new LogicCodeBlock.LogicCodeBlockCallback() {
                @Override
                public void next(int logicState) {
                    if (logicState == LogicCodeBlock.LogicState.CollectGoods.value) {
                        collectGoods(1);// 登录成功后，不管之前是否已经收藏，再次收藏该商品
                    }
                }
            });
        }
    }

    /**
     * 添加购物车
     */
    private void addToCart() {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
            int userId = (int) Utils.getUserLoginInfo().getUserId();
            int goodsId = mGoodsDetails.getGoodsId();
            int supplierId = mGoodsDetails.getSupplierId();
            int shopId = mGoodsDetails.getShopId();
            int goodsSkuId = mGoodsDetails.getGoodsSkuId();
            int goodsType = mGoodsDetails.getGoodsType();
            CLog.d("goodsSkuId = " + goodsSkuId);
            // 如果是sku商品则购买前弹出规格pop
            if (goodsType == 1) {
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SHOW_SPEC_POP));
            } else {
                CategoryApi.addToShoppingCart(mActivity, userId, goodsId, supplierId, shopId, goodsSkuId, 1, 0, new DialogCallback<GoodsStock>(mActivity) {

                    @Override
                    public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                        XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_sucs);
                        addCartAnim();
                        // 如果是从购物车进来的，添加购物车后通知刷新数据
                        if (mIsFromCart) {
                            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_REFRESH_SHOPPINGCART));
                        } else {
                            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SET_SHOPPINGCART_NUM, ++cartNum));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        // TODO: 2016/12/29 计入购物车失败情况的判断,基类中已经对错误进行了处理，此处不用做其他操作

                        //                        XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_failed);
                    }
                });
            }

        } else {
            XToastUtils.showShortToast(R.string.msg_login_to_add_goods);
            LogicCodeBlock.create().registerLogicCodeCallback(new LogicCodeBlock.LogicCodeBlockCallback() {
                @Override
                public void next(int logicState) {
                    if (logicState == LogicCodeBlock.LogicState.AddToCart.value) {
                        addToCart();
                    }
                }
            });
        }
    }


    public class GoodsViewPagerAdapter extends FragmentPagerAdapter {

        public GoodsViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public int getCount() {
            return mFragments != null ? mFragments.length : 0;
        }
    }

    /**
     * 控制viewPage是否可以滑动
     *
     * @param b
     */
    public void isViewPagerEnable(boolean b) {
        mViewpager.setPagingEnabled(b);
    }

    /**
     * 改变toolbar上不同状态
     *
     * @param open
     */
    public void changeToolbarStatus(boolean open) {

        int measuredHeight = mTabLayout.getMeasuredHeight();
        mTvDetailsToolbar.setVisibility(View.VISIBLE);
        if (open) {
            toolbarTranslate(mTvDetailsToolbar, 0f, measuredHeight);
            toolbarTranslate(mTabLayout, -measuredHeight, 0f);

        } else {
            toolbarTranslate(mTvDetailsToolbar, measuredHeight, 0f);
            toolbarTranslate(mTabLayout, 0f, -measuredHeight);
        }
    }

    /**
     * toolbar内容的平移动画
     *
     * @param view
     * @param toYValue
     */
    public void toolbarTranslate(View view, float fromYValue, float toYValue) {
        // 使用属性动画
        ObjectAnimator oa = new ObjectAnimator().ofFloat(view, "translationY", fromYValue, toYValue);
        oa.setDuration(500);
        oa.start();
    }

    /**
     * 收藏商品时的动画
     */
    public void collectGoodsAnim() {

        ScaleAnimation sa = new ScaleAnimation(1f, 1.2f, 1f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setFillAfter(true);
        sa.setDuration(200);
        sa.setRepeatMode(Animation.REVERSE);
        sa.setRepeatCount(1);
        mIvCollectGoods.startAnimation(sa);

        sa.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                mIvCollectGoods.setImageResource(isCollected ? R.drawable.icon_collection_selected : R.drawable.icon_collection);
                mTvCollectGoods.setTextColor(isCollected ? getResources().getColor(R.color.tv_red_login_bg) : getResources().getColor(R.color.color_707070));
            }
        });
    }


    private void addCartAnim() {
        ScaleAnimation sa = new ScaleAnimation(1f, 1.3f, 1f, 1.3f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setFillAfter(true);
        sa.setDuration(200);
        sa.setRepeatMode(Animation.REVERSE);
        sa.setRepeatCount(1);
        mRtvCartNum.startAnimation(sa);

    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        if (eventManager != null) {
            switch (eventManager.getEventCode()) {
                case LeEventCode.MSG_CODE_GET_GOODS_DETAILS_ERROR:
                    //网络问题或者服务器问题，则不能添加到购物车，也不能收藏
                    netError = true;
                    break;
                case LeEventCode.MSG_CODE_GET_GOODS_DETAILS_SUCS:
                    if (!mRefuse) {
                        mViewpager.setPagingEnabled(true);
                        setTabClickable(true);
                        netError = false;
                        mGoodsDetails = (GoodsDetails) eventManager.getData();
                        setState();
                    }
                    break;
                // 从商品信息页面添加商品后，刷新数据
                case LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART:
                    addCartAnim();
                    break;
                // 购物车数量改变或者重新登录后刷新数据
                case LeEventCode.MSG_CODE_SET_SHOPPINGCART_SUCS:
                    setCartNum();
                    break;
                // 获取商品规格pop选择的规格对应的goodsSkuId
                case LeEventCode.MSG_CODE_GOODS_SKU_ID:
                    mGoodsDetails.setGoodsSkuId((int) eventManager.getData());
                    break;
                // finish掉goodsActivity
                case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY:
                    mActivity.finish();
                    break;
            }

        }
    }

    /**
     * 当访问接口成功后，刷新页面状态
     */
    private void setState() {
        // 商品如果下架，显示已下架且不可点击
        mTvAddToCart.setEnabled(mGoodsDetails.getStatusCode() == 1 ? true : false);
        mTvAddToCart.setText(mGoodsDetails.getStatusCode() == 1 ? getResources().getString(R.string.add_to_shopping_cart) : getResources().getString(R.string.goods_off_the_shelf));
        mLlCollectGoods.setEnabled(true);
        mLlShoppingCart.setEnabled(true);
        isCollected = mGoodsDetails.getIsEnshrine() == 1 ? true : false;
        mIvCollectGoods.setImageResource(isCollected ? R.drawable.icon_collection_selected : R.drawable.icon_collection);
        mTvCollectGoods.setTextColor(isCollected ? getResources().getColor(R.color.tv_red_login_bg) : getResources().getColor(R.color.color_707070));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mSubscription != null) {
            mSubscription.unsubscribe();
        }
    }

    /**
     * 在此页面打开购物车，该fragment便隐藏了。此时不再接收eventBus发来的goodsDetail数据
     * 否则从打开的购物车在重新进入该fragment，该页面又会接收一次最新的goodsDetail数据，从而产生问题
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mRefuse = hidden;
    }


}
